package com.lh.web.controller;

import com.lh.common.entity.SysDeptEntity;
import com.lh.common.utils.Constant;
import com.lh.common.utils.Result;
import com.lh.web.service.SysDeptService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;


/**
 * 部门管理
 * @author FH
 * @date: 2020-04-09 10:17
 */
@RestController
@RequestMapping("/sys/dept")
@Api(value="SysDeptController",tags={"部门管理"})
public class SysDeptController extends AbstractController {

	@Autowired
	private SysDeptService sysDeptService;

	/**
	 * 列表
	 */
	@GetMapping("/list")
	@RequiresPermissions("sys:dept:list")
	@ApiOperation("列表")
	public Result<List<SysDeptEntity>> list(){
		List<SysDeptEntity> deptList = sysDeptService.queryList(new HashMap<>());

		return  Result.ok(deptList);
	}

	/**
	 * 选择部门(添加、修改菜单)
	 */
	@GetMapping("/select")
	@RequiresPermissions("sys:dept:select")
	@ApiOperation("选择部门(添加、修改菜单)")
	public Result<List<SysDeptEntity>> select(){
		List<SysDeptEntity> deptList = sysDeptService.queryList(new HashMap<>());

		//添加一级部门
		if(getUserId() == Constant.SUPER_ADMIN){
			SysDeptEntity root = new SysDeptEntity();
			root.setDeptId(0L);
			root.setName("一级部门");
			root.setParentId(-1L);
			root.setOpen(true);
			deptList.add(root);
		}

		return Result.ok(deptList);
	}

	/**
	 * 上级部门Id(管理员则为0)
	 */
	@GetMapping("/info")
	@RequiresPermissions("sys:dept:list")
	@ApiOperation("上级部门Id(管理员则为0)")
	public Result info(){
		long deptId = 0;
		if(getUserId() != Constant.SUPER_ADMIN){
			SysDeptEntity dept = sysDeptService.queryObject(getDeptId());
			deptId = dept.getParentId();
		}

		return Result.ok(deptId);
	}

	/**
	 * 信息
	 */
	@GetMapping("/info/{deptId}")
	@RequiresPermissions("sys:dept:info")
	@ApiOperation("信息")
	public Result<SysDeptEntity> info(@PathVariable("deptId") Long deptId){
		SysDeptEntity dept = sysDeptService.queryObject(deptId);

		return Result.ok(dept);
	}

	/**
	 * 保存
	 */
	@PostMapping("/save")
	@RequiresPermissions("sys:dept:save")
	@ApiOperation("保存")
	public Result save(@RequestBody SysDeptEntity dept){
		sysDeptService.save(dept);

		return Result.ok();
	}

	/**
	 * 修改
	 */
	@PostMapping("/update")
	@ApiOperation("修改")
	@RequiresPermissions("sys:dept:update")
	public Result update(@RequestBody SysDeptEntity dept){
		sysDeptService.update(dept);

		return Result.ok();
	}

	/**
	 * 删除
	 */
	@GetMapping("/delete")
	@ApiOperation("删除")
	@RequiresPermissions("sys:dept:delete")
	public Result delete(long deptId){
		//判断是否有子部门
		List<Long> deptList = sysDeptService.queryDetpIdList(deptId);
		if(deptList.size() > 0){
			return Result.error("请先删除子部门");
		}

		sysDeptService.delete(deptId);

		return Result.ok();
	}

}
